package com.tonyodev.fetch2.downloader;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @since 2021-05-20
 */
public class DownloadManagerCoordinator {
    private Object lock;
    private Map<Integer, FileDownloader> fileDownloaderMap;
    private String namespace;

    public DownloadManagerCoordinator(String namespace){
        this.namespace = namespace;
        this.lock = new Object();
        this.fileDownloaderMap = new LinkedHashMap();
    }

    public void interruptDownload(int downloadId) {
        synchronized(lock) {
            FileDownloader fileDownloader = (FileDownloader) fileDownloaderMap.get(downloadId);
            if (fileDownloader != null) {

                this.fileDownloaderMap.remove(downloadId);
            }
        }
    }


    public void addFileDownloader(int downloadId, FileDownloader fileDownloader) {
        synchronized(lock) {
            fileDownloaderMap.put(downloadId, fileDownloader);
        }
    }

    public void removeFileDownloader(int downloadId) {
        synchronized(lock) {
            fileDownloaderMap.remove(downloadId);
        }
    }

    public List<FileDownloader> getFileDownloaderList() {
        List<FileDownloader> downloaderList = new ArrayList<>();
        for (FileDownloader loader : fileDownloaderMap.values()){
            downloaderList.add(loader);
        }
        return downloaderList;
    }

    public boolean containsFileDownloader(int downloadId){
        boolean isContains = false;
        synchronized (lock){
            if(fileDownloaderMap.containsKey(downloadId)){
                isContains = true;
            }
        }
        return isContains;
    }

    public void clearAll() {
        synchronized(lock) {
            fileDownloaderMap.clear();
        }
    }
}
